<!-- 事件日志 -->
<template>
  <div class="dashboard-editor-container">
    <div style="display:flex;justify-content:space-between;">
      <partitionTree :nodeData="nodeData" :expandArray="expandArray" :addTemplate="false" :defaultExpandAll="false" dialogName="EventLog"
        @handleNodeClick="handleNodeClick" ref="partitionTree" @toggleVisibility="toggleVisibility">
      </partitionTree>
      <div :style="{ width: containerWidth }" class="box"
        style="background:#fff;border: 1px solid #ddd;border-radius: 4px;box-shadow: 0px 2px 4px rgba(0, 0, 0, 0.1);">
        <el-row style="background: #fff; padding: 16px 16px 0;">
          <connsearch ref="connsearch" :formOptions="formOptions" @search="search" @reset="reset"></connsearch>
          <div class="tabclick">
            <div class="tabitem" @click="handleClick()">
              <span><i :class="tab ? 'el-icon-arrow-up' : 'el-icon-arrow-down'"></i></span>
            </div>
          </div>
          <el-row>
            <el-tabs type="border-card" v-if="tab" style="margin-top:16px;" @tab-click="tabClick">
              <el-tab-pane label="按日统计趋势" lazy>
                <el-col :xs="24" :sm="24" :lg="24">
                  <barchart :chartData="barchartData" @barclick="echartsClick" title="按日统计趋势" />
                </el-col>
              </el-tab-pane>
              <el-tab-pane label="按资产名称统计分析" lazy>
                <el-col :xs="24" :sm="24" :lg="24">
                  <piechart :chartData="pie3Data" @pieclick="echartsClick" title="按资产名称统计分析" />
                </el-col>
              </el-tab-pane>
              <el-tab-pane label="按事件名称统计分析" lazy>
                <el-col :xs="24" :sm="24" :lg="24">
                  <piechart :chartData="pie4Data" @pieclick="echartsClick" title="按事件名称统计分析" />
                </el-col>
              </el-tab-pane>
              <el-tab-pane label="按事件等级统计分析" lazy>
                <el-col :xs="24" :sm="24" :lg="24">
                  <piechart :chartData="pie5Data" @pieclick="echartsClick" title="异常域名统计分析" />
                </el-col>
              </el-tab-pane>
            </el-tabs>
          </el-row>
          <el-col :xs="{ span: 24 }" :sm="{ span: 24 }" :md="{ span: 24 }" :lg="{ span: 24 }" :xl="{ span: 24 }"
            style="padding-right: 8px;margin:16px 0;">
            <el-table stripe border :data="tableData" style="width: 100%; margin-top: 15px">
              <el-table-column label="序号" width="60" type="index"
                :index='(index) => { return (index + 1) + (this.pageNum - 1) * this.pageSize }'> </el-table-column>
              <el-table-column label="部门" show-overflow-tooltip prop="Department" width="120px"></el-table-column>
              <el-table-column label="资产名称" show-overflow-tooltip prop="DeviceName" width="160px"></el-table-column>
              <el-table-column label="使用者" show-overflow-tooltip prop="UserName" width="120px"></el-table-column>
              <el-table-column label="发生时间" show-overflow-tooltip prop="TransTime" width="160px"></el-table-column>
              <el-table-column label="事件名称" show-overflow-tooltip prop="EventID" width="160px">
                <template slot-scope="{row}">
                  {{ getEventLabel(row.EventID) }}
                </template>
              </el-table-column>
              <el-table-column label="事件等级" show-overflow-tooltip prop="Level" width="100">
                <template slot-scope="{row}">
                  <span style="color:#F56C6C" v-show="row.EventLevel == '1'">紧急</span>
                  <span style="color:#E6A23C" v-show="row.EventLevel == '2'">重要</span>
                  <span style="color:#909399" v-show="row.EventLevel == '3'">默认</span>
                  <span style="color:#409EFF" v-show="row.EventLevel == '4'">普通</span>
                  <span style="color:#67C23A" v-show="row.EventLevel == '5'">告知</span>
                </template>
              </el-table-column>
              <el-table-column label="描述信息" show-overflow-tooltip prop="Descp"></el-table-column>
              <el-table-column label="确认状态" show-overflow-tooltip prop="IsAck" width="100">
                <template slot-scope="{row}">
                  <span style="color:#909399" v-show="row.IsACK == '0'">未确认</span>
                  <span style="color:#67C23A" v-show="row.IsACK == '1'">已确认</span>
                </template>
              </el-table-column>
              <el-table-column label="操作" width="120px" fixed="right">
                <template slot="header" slot-scope="scope">
                  <el-button size="mini" :type="!confirmThisPage ? 'info' : 'primary'" :disabled="!confirmThisPage"
                    @click="changeMailGlobalAll(scope.row)">确认本页</el-button>
                </template>
                <template slot-scope="scope">
                  <el-button size="mini" :type="scope.row.IsACK == '1' ? 'info' : 'primary'"
                    :disabled="scope.row.IsACK == '1'" @click="changeMailGlobal(scope.row)">确 认</el-button>
                </template>
              </el-table-column>
            </el-table>
            <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page=pageNum
              :page-size=pageSize background layout="total, prev, pager, sizes, next, jumper" :total="total">
            </el-pagination>
          </el-col>
        </el-row>
      </div>
    </div>
  </div>
</template>

<script>
import Cookies from 'js-cookie'
import connsearch from "@/components/connSearch";
import barchart from "./components/barchart.vue";
import piechart from "./components/piechart.vue";
import { parseTime, GetDeviceTree2 } from "@/utils/index.js";
import { connrequest } from "@/api/firstPage.js"
import partitionTree from "@/components/partitionTree";
export default {
  components: { connsearch, barchart, piechart, partitionTree },
  data() {
    let that = this
    return {
      activeName: "",
      tabTitle: '按日统计趋势',
      pageNum: 1,
      pageSize: 10,
      total: 0,
      tab: false,
      confirmThisPage: false,
      barchartData: { xAxis: [], series: [] },
      pie3Data: [],
      pie4Data: [],
      pie5Data: [],
      nodeData: [],
      expandArray: [],
      containerWidth: 'calc(100% - 275px)',
      tableData: [],
      eventList: [],
      searchform: {},
      options: {},
      nodeobj: {},
      searchobj: {},
      echartsobj: {},
      formOptions: [
        {
          col: 8,
          hidden: false,
          label: "日期", // label文字
          prop: "timeRange", // 字段名
          initValue: [], // 字段初始值,
          element: "el-date-picker", // 指定elementui组件
          type: "", // 日期选择类型,
          events: {
            input(val) {
              that.searchform.timeRange = val
            },
          },
        },
        {
          col: 4,
          hidden: false,
          label: "事件等级", // label文字
          prop: "Level", // 字段名
          element: "el-select", // 指定elementui组件
          initValue: '', // 字段初始值,
          placeholder: "请选择等级", // elementui组件属性
          options: [
            { label: '全部', value: '' },
            { label: '紧急', value: 1 },
            { label: '重要', value: 2 },
            { label: '默认', value: 3 },
            { label: '普通', value: 4 },
            { label: '告知', value: 5 }
          ],
          rules: [], // elementui组件属性
          events: {
            input(val) {
              that.searchform.Level = val
            },
          },
        },
        {
          col: 6,
          hidden: false,
          label: "事件名称", // label文字
          prop: "EventID", // 字段名
          element: "el-select", // 指定elementui组件
          initValue: '', // 字段初始值,
          placeholder: "请选择事件名称", // elementui组件属性
          rules: [], // elementui组件属性
          events: {
            input(val) {
              that.searchform.EventID = val
            },
          },
        },
        {
          col: 6,
          hidden: false,
          label: "确认状态", // label文字
          prop: "IsAck", // 字段名
          element: "el-select", // 指定elementui组件
          initValue: 0, // 字段初始值,
          placeholder: "请选择等级", // elementui组件属性
          options: [
            { label: '全部', value: 0 },
            { label: '未确认', value: 1 },
            { label: '已确认', value: 2 },
          ],
          rules: [], // elementui组件属性
          events: {
            input(val) {
              that.searchform.IsAck = val
            },
          },
        },
        {
          col: 8,
          label: "描述信息", // label文字
          prop: "Descp", // 字段名
          element: "el-input", // 指定elementui组件
          initValue: "", // 字段初始值,
          placeholder: "请输入描述信息,支持模糊查询。", // elementui组件属性
          maxlength: 50,
          rules: [], // elementui组件属性
          events: {
            input(val) {
              that.searchform.Descp = val
            },
          },
        },
      ],
    };
  },
  //生命周期 - 创建完成（访问当前this实例）
  created() {
    this.pageSize = (Cookies.get('Zhuoguan_DefaultPageLength') || 10) * 1;

    let endTime = new Date(new Date().setHours(0, 0, 0, 0)).getTime()
    let startTime = endTime - ((Cookies.get('Zhuoguan_DefaultLogDays') || 7) * 24 * 3600 * 1000);
    let arr = [parseTime(startTime), '']
    this.formOptions.map(item => {
      if (item.label === '日期') {
        item.initValue = arr
      }
    })
    this.$set(this.searchform, 'timeRange', arr)
    this.$set(this.searchform, 'Level', '')
    this.$set(this.searchform, 'IsAck', 0)
    this.getData()
  },
  //生命周期 - 挂载完成（访问DOM元素）
  mounted() {
    this.initData()
    this.GetParamDictEvent()
  },
  methods: {
    async initData(searchobj = {}) {
      try {
        const { DeviceTree } = await GetDeviceTree2('EventLog',
        {
          StartTime: this.searchform.timeRange?.[0] || '',
          EndTime: this.searchform.timeRange?.[1] || '',
          Level: this.searchform.Level,
          EventID: this.searchform.EventID,
          IsAck: this.searchform.IsAck,
          Descp: this.searchform.Descp || '',
          DeviceUUID: this.searchform.DeviceUUID || '',
          ...searchobj
        })
        this.nodeData = DeviceTree
        this.expandArray = [DeviceTree?.[0]?.Name]
      } catch (error) {
        this.$message.error('加载设备树数据失败');
      }
    },
    handleNodeClick(nodeData) {
      this.pageNum = 1
      this.nodeobj = { DepartmentID: nodeData.data.isDevice ? nodeData.data.DepartmentID : nodeData.data.ID, DeviceUUID: nodeData.data.isDevice ? nodeData.data.DeviceUUID : '' }
      this.echartsobj = {}
      this.getData({ ...this.searchobj, ...this.nodeobj })
    },
    toggleVisibility(isHidden) {
      if (isHidden)
        this.containerWidth = '100%';
      else
        this.containerWidth = 'calc(100% - 275px)';
    },
    // 获取事件定义
    async GetParamDictEvent() {
      const data = {
        Paging: {
          QueryPageNo: 1,
          QueryPageLength: 100000000
        }
      }
      const res = await connrequest('GetParamDictEvent', data)
      let arr = []
      res.Data.map(item => {
        arr.push({ label: item.AlarmDescp, value: item.EventID })
      })
      // arr
      this.formOptions.map(item => {
        if (item.label === '事件名称') {
          item.options = arr
          item.initValue = arr[0]?.value
        }
      })
      arr.unshift({ label: '全部', value: '' });
      this.eventList = arr
    },
    getEventLabel(eventID) {
      return this.eventList.find(item => item.value === eventID)?.label || null;
    },
    async changeMailGlobal(row) {
      const data = {
        Data: [row.AutoID]
      }
      const res = await connrequest('ConfirmEvent', data)
      if (res.Status.StatusCode === 0) {
        await this.getData({ ...this.searchobj, ...this.echartsobj, ...this.nodeobj })
        this.$message.success('确认成功')
      }
    },
    async changeMailGlobalAll() {
      const arr = this.tableData.map(item => item.AutoID);
      const data = {
        Data: arr
      }
      const res = await connrequest('ConfirmEvent', data)
      if (res.Status.StatusCode === 0) {
        await this.getData({ ...this.searchobj, ...this.echartsobj, ...this.nodeobj })
        this.$message.success('确认成功')
      }
    },
    // 获取所有数据
    getData(searchobj = {}) {
      this.GetEventLog(searchobj)
      switch (this.tabTitle) {
        case '按日统计趋势':
          this.GetEventLogSumGroupByDate(searchobj)
          break;
        case '按资产名称统计分析':
          this.GetEventLogSumGroupByDevice(searchobj)
          break;
        case '按事件名称统计分析':
          this.GetEventLogSumGroupByEventID(searchobj)
          break;
        default:
          this.GetEventLogSumGroupByLevel(searchobj)
          break;
      }
    },
    echartsClick(val, title) {
      this.pageNum = 1
      if (title === '按日统计趋势') {
        this.echartsobj = { StartTime: `${val} 00:00:00`, EndTime: `${val} 23:59:59` }
        this.GetEventLog({ ...this.searchobj, ...this.nodeobj, ...this.echartsobj })
      } else if (title === '按资产名称统计分析') {
        this.echartsobj = { DeviceName: val }
        this.GetEventLog({ ...this.searchobj, ...this.nodeobj, ...this.echartsobj })
      } else if (title === '按事件名称统计分析') {
        const eventListObject = Object.fromEntries(this.eventList.map(item => [item.label, item.value]));
        this.echartsobj = { EventID: eventListObject[val] }
        this.GetEventLog({ ...this.searchobj, ...this.nodeobj, ...this.echartsobj })
      } else {
        let Level = { 紧急: 1, 重要: 2, 默认: 3, 普通: 4, 告知: 5 }
        this.echartsobj = { Level: Level[val] }
        this.GetEventLog({ ...this.searchobj, ...this.nodeobj, ...this.echartsobj })
      }
      this.initData(this.echartsobj)
    },
    tabClick(row) {
      this.tabTitle = row.label
      switch (row.label) {
        case '按日统计趋势':
          this.GetEventLogSumGroupByDate({ ...this.searchobj, ...this.nodeobj })
          break;
        case '按资产名称统计分析':
          this.GetEventLogSumGroupByDevice({ ...this.searchobj, ...this.nodeobj })
          break;
        case '按事件名称统计分析':
          this.GetEventLogSumGroupByEventID({ ...this.searchobj, ...this.nodeobj })
          break;
        default:
          this.GetEventLogSumGroupByLevel({ ...this.searchobj, ...this.nodeobj })
          break;
      }
    },
    // 获取事件日志列表
    async GetEventLog(searchobj = {}) {
      const data = {
        Paging: {
          QueryPageNo: this.pageNum,
          QueryPageLength: this.pageSize
        },
        Filter: {
          StartTime: this.searchform.timeRange?.[0] || '',
          EndTime: this.searchform.timeRange?.[1] || '',
          Level: this.searchform.Level,
          EventID: this.searchform.EventID,
          IsAck: this.searchform.IsAck,
          Descp: this.searchform.Descp || '',
          DeviceUUID: this.searchform.DeviceUUID || '',
          ...searchobj
        }
      }
      const res = await connrequest('GetEventLog', data)
      this.confirmThisPage = false
      res.Data = res.Data || []
      res.Data = res.Data.map(item => {
        item.TransTime = parseTime(item.TransTime)
        // 如果存在未确认的数据，确认本页按钮显示可用
        if (item.IsACK === 0) {
          this.confirmThisPage = true
        }
        return item
      })
      this.$nextTick(() => {
        this.tableData = res.Data
        this.total = res.Paging.TotalCount
      })
    },
    // 获取事件日期统计
    async GetEventLogSumGroupByDate(searchobj = {}) {
      let xAxis = []
      let t1 = []
      let t2 = []
      let t3 = []
      let t4 = []
      let t5 = []
      const data = {
        Filter: {
          StartTime: this.searchform.timeRange?.[0] || '',
          EndTime: this.searchform.timeRange?.[1] || '',
          Level: this.searchform.Level,
          EventID: this.searchform.EventID,
          IsAck: this.searchform.IsAck,
          DeviceUUID: this.searchform.DeviceUUID || '',
          Descp: this.searchform.Descp || '',
          ...searchobj
        }
      }
      const res = await connrequest('GetEventLogSumGroupByDate', data)
      res.Data = res.Data || []
      res.Data.map(item => {
        xAxis.push(item.TransDate)
        t1.push(item[1])
        t2.push(item[2])
        t3.push(item[3])
        t4.push(item[4])
        t5.push(item[5])
      })
      this.barchartData = { xAxis, t1, t2, t3, t4, t5 }
    },
    // 按事件资产统计分析
    async GetEventLogSumGroupByDevice(searchobj = {}) {
      let arr = []
      const data = {
        Filter: {
          StartTime: this.searchform.timeRange?.[0] || '',
          EndTime: this.searchform.timeRange?.[1] || '',
          Level: this.searchform.Level,
          EventID: this.searchform.EventID,
          IsAck: this.searchform.IsAck,
          DeviceUUID: this.searchform.DeviceUUID || '',
          Descp: this.searchform.Descp || '',
          ...searchobj
        }
      }
      const res = await connrequest('GetEventLogSumGroupByDevice', data)
      res.Data = res.Data || []
      res.Data.map(item => {
        arr.push({ name: item.Name, value: item.Count })
      })
      this.pie3Data = arr
    },
    // 按事件名称统计分析
    async GetEventLogSumGroupByEventID(searchobj = {}) {
      let arr = []
      const data = {
        Filter: {
          StartTime: this.searchform.timeRange?.[0] || '',
          EndTime: this.searchform.timeRange?.[1] || '',
          Level: this.searchform.Level,
          EventID: this.searchform.EventID,
          IsAck: this.searchform.IsAck,
          DeviceUUID: this.searchform.DeviceUUID || '',
          Descp: this.searchform.Descp || '',
          ...searchobj
        }
      }
      const res = await connrequest('GetEventLogSumGroupByEventID', data)
      res.Data = res.Data || []
      res.Data.map(item => {
        arr.push({ name: this.getEventLabel(item.ClassID) || '未知', value: item.Count })
      })
      this.pie4Data = arr
    },
    // 按事件等级统计分析
    async GetEventLogSumGroupByLevel(searchobj = {}) {
      const Level = ['紧急', '重要', '默认', '普通', '告知'];
      const colorMap = {
        '紧急': '#F56C6C',
        '重要': '#E6A23C',
        '默认': '#909399',
        '普通': '#409EFF',
        '告知': '#67C23A'
      };
      const data = {
        Filter: {
          StartTime: this.searchform.timeRange?.[0] || '',
          EndTime: this.searchform.timeRange?.[1] || '',
          Level: this.searchform.Level,
          EventID: this.searchform.EventID,
          IsAck: this.searchform.IsAck,
          DeviceUUID: this.searchform.DeviceUUID || '',
          Descp: this.searchform.Descp || '',
          ...searchobj
        }
      };
      const res = await connrequest('GetEventLogSumGroupByLevel', data);
      this.pie5Data = (res.Data || []).map(item => ({
        name: Level[item.ClassID - 1] || '未知',
        value: item.Count,
        color: colorMap[Level[item.ClassID - 1] || '未知'] || '#CCCCCC'
      }));
    },
    // 搜索
    search(val) {
      this.pageNum = 1
      this.searchobj = { ...val }
      this.searchform = { ...val }
      if (this.searchform.timeRange) {
        this.searchobj = { ...this.searchobj, StartTime: this.searchform?.timeRange[0] || '', EndTime: this.searchform?.timeRange[1] || '' }
      }
      this.getData({ ...this.echartsobj, ...this.searchobj, ...this.nodeobj })
      this.initData({...this.searchobj})
    },
    // 重置
    reset() {
      let endTime = new Date(new Date().setHours(0, 0, 0, 0)).getTime()
      let startTime = endTime - ((Cookies.get('Zhuoguan_DefaultLogDays') || 7) * 24 * 3600 * 1000);
      let arr = [parseTime(startTime), '']
      this.pageNum = 1
      this.formOptions = this.formOptions.map(item => {
        if (item.label === "日期") {
          item.initValue = arr
        } else if (item.label === "确认状态") {
          item.initValue = 0
        } else {
          item.initValue = ""
        }
        return item
      })
      this.searchform = {}
      this.echartsobj = {}
      this.searchobj = {}
      this.nodeobj = {}
      this.$set(this.searchform, 'timeRange', arr)
      this.$set(this.searchform, 'IsAck', 0)
      this.$refs.connsearch.addInitValue()
      this.getData()
      this.initData()
    },
    handleSizeChange(pageSize) {
      this.pageSize = pageSize
      this.pageNum = 1
      this.GetEventLog({ ...this.searchobj, ...this.echartsobj, ...this.nodeobj })
    },
    handleCurrentChange(pageNum) {
      this.pageNum = pageNum
      this.GetEventLog({ ...this.searchobj, ...this.echartsobj, ...this.nodeobj })
    },
    handleClick() {
      this.tab = !this.tab
    },
  },
};
</script>
<style lang="scss" scoped>
@import "./components/css/conncss.scss";
</style>